// API配置
const API_KEY = 'SDsBAspdPbwGLHi4a';
const CITY = 'dongguan';
const BASE_URL = 'https://api.seniverse.com/v3';

// 天气图标映射
const weatherIcons = {
    '晴': 'fas fa-sun',
    '多云': 'fas fa-cloud-sun',
    '阴': 'fas fa-cloud',
    '小雨': 'fas fa-cloud-rain',
    '中雨': 'fas fa-cloud-showers-heavy',
    '大雨': 'fas fa-cloud-showers-heavy',
    '雷阵雨': 'fas fa-bolt',
    '雪': 'fas fa-snowflake',
    '雾': 'fas fa-smog',
    '霾': 'fas fa-smog'
};

// 更新时间显示
function updateCurrentTime() {
    const now = new Date();
    const options = {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    };
    document.getElementById('update-time').textContent = now.toLocaleString('zh-CN', options);
}

// 获取实时天气数据
async function getCurrentWeather() {
    try {
        const url = `${BASE_URL}/weather/now.json?key=${API_KEY}&location=${CITY}&language=zh-Hans&unit=c`;
        const response = await fetch(url);
        const data = await response.json();
        
        if (data.results && data.results.length > 0) {
            const weatherData = data.results[0].now;
            document.getElementById('temperature').textContent = weatherData.temperature;
            document.getElementById('weather-text').textContent = weatherData.text;
            
            // 设置天气图标
            const iconElement = document.getElementById('weather-icon');
            const iconClass = weatherIcons[weatherData.text] || 'fas fa-question';
            iconElement.className = iconClass;
            
            // 模拟湿度和风速数据
            document.getElementById('humidity').textContent = Math.floor(Math.random() * 40 + 40); // 40-80%
            document.getElementById('wind-speed').textContent = Math.floor(Math.random() * 20 + 5); // 5-25 km/h
            document.getElementById('wind-direction').textContent = ['东', '南', '西', '北'][Math.floor(Math.random() * 4)];
        }
    } catch (error) {
        console.error('获取实时天气数据失败:', error);
        document.getElementById('weather-text').textContent = '数据加载失败';
    }
}

// 获取天气预报数据
async function getWeatherForecast() {
    try {
        const url = `${BASE_URL}/weather/daily.json?key=${API_KEY}&location=${CITY}&language=zh-Hans&unit=c&start=0&days=3`;
        const response = await fetch(url);
        const data = await response.json();
        
        if (data.results && data.results.length > 0 && data.results[0].daily) {
            const forecastData = data.results[0].daily;
            const dayNames = ['今天', '明天', '后天'];
            
            forecastData.forEach((day, index) => {
                const dayElement = document.getElementById(`day${index + 1}`);
                if (dayElement) {
                    dayElement.querySelector('.date').textContent = dayNames[index];
                    dayElement.querySelector('.day-weather span').textContent = `白天: ${day.text_day}`;
                    dayElement.querySelector('.night-weather span').textContent = `夜间: ${day.text_night}`;
                    dayElement.querySelector('.temp-range').textContent = `${day.low}°C ~ ${day.high}°C`;
                    
                    // 设置白天天气图标
                    const dayIcon = dayElement.querySelector('.day-weather .weather-icon');
                    dayIcon.className = weatherIcons[day.text_day] || 'fas fa-question';
                    
                    // 设置夜间天气图标
                    const nightIcon = dayElement.querySelector('.night-weather .weather-icon');
                    nightIcon.className = weatherIcons[day.text_night] || 'fas fa-question';
                }
            });
        }
    } catch (error) {
        console.error('获取天气预报数据失败:', error);
    }
}

// 获取生活指数数据
async function getLifestyleIndices() {
    try {
        // 模拟生活指数数据
        const indicesData = {
            'dressing-index': '建议穿薄外套，早晚温差较大',
            'uv-index': '紫外线较强，外出请做好防晒措施',
            'car-wash-index': '天气良好，适合洗车',
            'travel-index': '天气适宜，是出游的好时机',
            'flu-index': '温差较大，注意增减衣物预防感冒',
            'sport-index': '天气较好，适合户外运动'
        };
        
        // 更新页面显示
        Object.entries(indicesData).forEach(([id, value]) => {
            const element = document.getElementById(id);
            if (element) {
                element.textContent = value;
            }
        });
    } catch (error) {
        console.error('获取生活指数数据失败:', error);
    }
}

// 刷新天气数据的函数
async function refreshWeatherData() {
    const refreshBtn = document.getElementById('refresh-btn');
    
    // 添加刷新动画
    refreshBtn.classList.add('refreshing');
    refreshBtn.disabled = true;
    
    try {
        // 更新时间
        updateCurrentTime();
        
        // 并行获取所有数据
        await Promise.all([
            getCurrentWeather(),
            getWeatherForecast(),
            getLifestyleIndices()
        ]);
        
        // 显示刷新成功的提示 - 使用新的刷新通知函数
        showRefreshNotification();
    } catch (error) {
        console.error('刷新天气数据失败:', error);
        showNotification('更新失败，请稍后重试', 'error');
    } finally {
        // 移除刷新动画，恢复按钮状态
        setTimeout(() => {
            refreshBtn.classList.remove('refreshing');
            refreshBtn.disabled = false;
        }, 1000);
    }
}

// 显示刷新通知 - 新函数
function showRefreshNotification() {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = 'refresh-notification';
    notification.textContent = '刷新完成！温馨提醒，请不要多次刷新，不然天气数据会无法请求出来！';
    
    // 添加样式 - 浅绿色气泡效果
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        left: 50%;
        transform: translateX(-50%) translateY(-100px) scale(0.8);
        background-color: rgba(144, 238, 144, 0.9);
        color: #333;
        padding: 16px 24px;
        border-radius: 25px;
        font-size: 16px;
        font-weight: bold;
        text-align: center;
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        z-index: 1000;
        opacity: 0;
        transition: all 0.5s cubic-bezier(0.68, -0.55, 0.27, 1.55);
        max-width: 90%;
        word-wrap: break-word;
    `;
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 触发重排以确保动画效果
    void notification.offsetWidth;
    
    // 显示通知 - 带有动画
    notification.style.transform = 'translateX(-50%) translateY(0) scale(1)';
    notification.style.opacity = '1';
    
    // 显示一段时间后开始淡出动画
    setTimeout(() => {
        notification.style.transform = 'translateX(-50%) translateY(-20px) scale(0.95)';
        notification.style.opacity = '0';
        
        // 动画结束后移除元素
        setTimeout(() => {
            if (document.body.contains(notification)) {
                document.body.removeChild(notification);
            }
        }, 500);
    }, 4000); // 显示4秒后开始淡出
}

// 显示通知（保留原有函数用于错误通知）
function showNotification(message, type = 'success') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.textContent = message;
    
    // 添加样式
    notification.style.position = 'fixed';
    notification.style.top = '80px';
    notification.style.right = '20px';
    notification.style.padding = '12px 20px';
    notification.style.borderRadius = '8px';
    notification.style.color = 'white';
    notification.style.fontWeight = 'bold';
    notification.style.zIndex = '1000';
    notification.style.opacity = '0';
    notification.style.transition = 'opacity 0.3s ease';
    
    // 根据类型设置背景色
    if (type === 'success') {
        notification.style.backgroundColor = 'rgba(76, 175, 80, 0.9)';
    } else {
        notification.style.backgroundColor = 'rgba(244, 67, 54, 0.9)';
    }
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 显示通知
    setTimeout(() => {
        notification.style.opacity = '1';
    }, 10);
    
    // 3秒后隐藏通知
    setTimeout(() => {
        notification.style.opacity = '0';
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 3000);
}

// 页面加载时初始化
window.addEventListener('load', () => {
    updateCurrentTime();
    getCurrentWeather();
    getWeatherForecast();
    getLifestyleIndices();
    
    // 为刷新按钮添加点击事件
    const refreshBtn = document.getElementById('refresh-btn');
    if (refreshBtn) {
        refreshBtn.addEventListener('click', refreshWeatherData);
    }
    
    // 每10分钟自动更新数据
    setInterval(() => {
        refreshWeatherData();
    }, 10 * 60 * 1000);
});